package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
@RabbitListener(queues = "stock.release.stock.queue")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 12
         wareId: 1
         */
        QueryWrapper<WareSkuEntity> wareSkuEntityQueryWrapper = new QueryWrapper<WareSkuEntity>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wareSkuEntityQueryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wareSkuEntityQueryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), wareSkuEntityQueryWrapper);

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 判断如果还没有这条库存记录，就进行新增
        List<WareSkuEntity> wareSkuEntityList = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId)
                .eq("ware_id", wareId));
        if (wareSkuEntityList != null && wareSkuEntityList.size() > 0) {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        } else {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // TODO:远程查询sku的名字，如果远程调用失败，整个事务无需回滚
            // TODO:还可以用什么方法让异常出现以后不回滚呢？留到高级部分讲解
            try {
                R info = this.productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch(Exception e) {}

            this.baseMapper.insert(wareSkuEntity);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map((skuId) -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long count = this.baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : (count > 0));

            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为指定的订单锁定库存
     * (rollbackFor = NoStockException.class)
     * 默认只要是运行时异常都会回滚
     *
     * 库存解锁的场景
     * 1）、下订单成功，订单过期没有支付被系统自动取消。都要解锁库存
     * 2）、下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单的详情
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());

        this.orderTaskService.save(taskEntity);
        // 1、按照下单的收货地址，找到一个就近仓库，锁住库存
        // 1、找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();

            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            // 查询这个商品在哪里有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());

            return stock;
        }).collect(Collectors.toList());

        // 2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            Integer num = hasStock.getNum();

            if (wareIds == null || wareIds.size() == 0) {
                // 没有任何仓库有库存
                throw new NoStockException(skuId);
            }
            // 1、如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给MQ
            // 2、如果锁定库存失败，前面保存的工作单信息就回滚了。发送出去的消息，即使要解锁记录，由于去数据库查不到id。所以就不用解锁
            for (Long wareId : wareIds) {
                // 成功就返回1，否则就是0行受影响
                Long count = this.baseMapper.lockSkuStock(skuId, wareId, num);
                if (count == 1) {
                    // 锁库存成功
                    skuStocked = true;
                    // TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    this.orderTaskDetailService.save(entity);

                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());

                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, detailTo);
                    // 不能只发id，防止回滚后找不到数据
                    lockedTo.setDetail(detailTo);

                    this.rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                } else {
                    // 锁失败，继续重试下一个仓库
                }
            }
            if (skuStocked == false) {
                // 所有仓库的锁库存尝试均失败
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {

        // 库存工作单的id
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        // 解锁
        // 1、查询数据库关于这个订单的锁定库存信息
        /**
         * 有：证明库存锁定成功了
         *      解锁：订单情况
         *          1、没有这个订单，必须解锁
         *          2、有这个订单，不是解锁库存
         *              订单状态：已取消：解锁库存
         *                      没取消：不能解锁
         */
        // 没有：库存锁定失败了，库存回滚了，这种情况无需解锁
        WareOrderTaskDetailEntity byId = this.orderTaskDetailService.getById(detailId);
        if (byId != null) {
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = this.orderTaskService.getById(id);
            // 根据订单号查询订单的状态
            String orderSn = taskEntity.getOrderSn();

            R r = this.orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {});
                if (data == null || data.getStatus() == 4) {
                    // 订单不存在
                    // 订单已经被取消了，才能解锁库存
                    if (byId.getLockStatus() == 1) {
                        // 当前库存工作单详情，状态1    已锁定但是未解锁才可以解锁
                        this.unlockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 消息拒绝以后重新放到队列里面，让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        } else {
            // 无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期，查订单状态是新建状态，程序什么都不会做
     * 导致卡顿的订单，永远不能解锁库存
     * @param orderTo
     */
    @Override
    @Transactional
    public void unlockStock(OrderTo orderTo) {

        String orderSn = orderTo.getOrderSn();
        // 可以查一下订单的最新状态，但没必要，进入这个方法已经是最新的订单状态
        // 一定要查询最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity task = this.orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        // 按照工作单找到所有没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> entities = this.orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            this.unlockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

//    @RabbitHandler
//    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
//
//        try {
//            System.out.println("收到解锁库存的消息");
//            // 库存工作单的id
//            StockDetailTo detail = to.getDetail();
//            Long detailId = detail.getId();
//            // 解锁
//            // 1、查询数据库关于这个订单的锁定库存信息
//            /**
//             * 有：证明库存锁定成功了
//             *      解锁：订单情况
//             *          1、没有这个订单，必须解锁
//             *          2、有这个订单，不是解锁库存
//             *              订单状态：已取消：解锁库存
//             *                      没取消：不能解锁
//             */
//            // 没有：库存锁定失败了，库存回滚了，这种情况无需解锁
//            WareOrderTaskDetailEntity byId = this.orderTaskDetailService.getById(detailId);
//            if (byId != null) {
//                // 解锁
//                Long id = to.getId();
//                WareOrderTaskEntity taskEntity = this.orderTaskService.getById(id);
//                // 根据订单号查询订单的状态
//                String orderSn = taskEntity.getOrderSn();
//
//                R r = this.orderFeignService.getOrderStatus(orderSn);
//                if (r.getCode() == 0) {
//                    // 订单数据返回成功
//                    OrderVo data = r.getData(new TypeReference<OrderVo>() {});
//                    if (data == null || data.getStatus() == 4) {
//                        // 订单不存在
//                        // 订单已经被取消了，才能解锁库存
//                        this.unlockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
//                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//                    }
//                } else {
//                    // 消息拒绝以后重新放到队列里面，让别人继续消费解锁
//                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//                }
//            } else {
//                // 无需解锁
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//            }
//        } catch (Exception e) {
//            // 消息拒绝以后重新放到队列里面，让别人继续消费解锁
//            System.out.println("错误。。。" + e.getMessage());
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//        }
//    }

    /**
     * 1、库存自动解锁
     * 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚，之前锁定的库存就要自动解锁
     * 2、订单失败
     * 锁库存失败
     *
     * 只要解锁库存的消息失败，一定要告诉服务解锁失败
     */
    private void unlockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 库存解锁
        this.baseMapper.unlockStock(skuId, wareId, num);
        // 更新库存工作单的状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        // 变为已解锁状态
        entity.setLockStatus(2);

        this.orderTaskDetailService.updateById(entity);
    }
}